<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="loadUsers">刷新</el-button>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="用户类型">
              <el-select
                v-model="searchForm.type"
                placeholder="请选择"
                clearable
                @clear="handleSearch"
                style="width: 100%"
              >
                <el-option label="微信用户" value="weixin" />
                <el-option label="游客" value="guest" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="平台">
              <el-select
                v-model="searchForm.platform"
                placeholder="请选择"
                clearable
                @clear="handleSearch"
                style="width: 100%"
              >
                <el-option label="微信小程序" value="mp-weixin" />
                <el-option label="H5" value="h5" />
                <el-option label="App" value="app-plus" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择"
                clearable
                @clear="handleSearch"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row" v-if="stats">
        <el-col :span="6">
          <el-statistic title="总用户数" :value="stats.total" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="微信用户" :value="stats.weixinCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="游客用户" :value="stats.guestCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日新增" :value="stats.todayCount" />
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="usersList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column
          prop="userId"
          label="用户ID"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'weixin' ? 'success' : 'info'">
              {{ row.type === "weixin" ? "微信" : "游客" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="openid"
          label="OpenID"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="nickname" label="昵称" width="150" />
        <el-table-column prop="platform" label="平台" width="120">
          <template #default="{ row }">
            <el-tag size="small">
              {{ getPlatformName(row.platform) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" width="180" />
        <el-table-column
          prop="lastLoginIp"
          label="登录IP"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="lastLoginUserAgent"
          label="User-Agent"
          width="250"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span :title="row.lastLoginUserAgent">
              {{ row.lastLoginUserAgent || "-" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";

const loading = ref(false);
const usersList = ref([]);
const stats = ref(null);

const searchForm = ref({
  type: "",
  platform: "",
  status: undefined,
});

const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});

// 加载用户列表
async function loadUsers() {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
    };

    if (searchForm.value.type) {
      params.type = searchForm.value.type;
    }

    if (searchForm.value.platform) {
      params.platform = searchForm.value.platform;
    }

    if (searchForm.value.status !== undefined) {
      params.status = searchForm.value.status;
    }

    const res = await request.get("/users", { params });

    usersList.value = res.list || [];
    pagination.value.total = res.total || 0;

    // 加载统计信息
    loadStats();
  } catch (error) {
    ElMessage.error(error.message || "加载失败");
  } finally {
    loading.value = false;
  }
}

// 加载统计信息
async function loadStats() {
  try {
    const res = await request.get("/users/stats");
    stats.value = res;
  } catch (error) {
    console.error("加载统计信息失败:", error);
  }
}

// 搜索
function handleSearch() {
  pagination.value.page = 1;
  loadUsers();
}

// 重置
function handleReset() {
  searchForm.value = {
    type: "",
    platform: "",
    status: undefined,
  };
  handleSearch();
}

// 切换状态
function handleToggleStatus(row) {
  const newStatus = row.status === 1 ? 0 : 1;
  const action = newStatus === 1 ? "启用" : "禁用";

  ElMessageBox.confirm(`确定要${action}用户 ${row.userId} 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await request.put(`/users/${row.userId}/status`, { status: newStatus });
        ElMessage.success(`${action}成功`);
        loadUsers();
      } catch (error) {
        ElMessage.error(error.message || `${action}失败`);
      }
    })
    .catch(() => {
      // 用户取消
    });
}

// 删除用户
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.userId} 吗？删除后该用户的所有数据（包括收藏）将被删除。`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        await request.delete(`/users/${row.userId}`);
        ElMessage.success("删除成功");
        loadUsers();
      } catch (error) {
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
}

// 获取平台名称
function getPlatformName(platform) {
  const platformMap = {
    "mp-weixin": "微信小程序",
    h5: "H5",
    "app-plus": "App",
  };
  return platformMap[platform] || platform || "-";
}

// 分页大小改变
function handleSizeChange(size) {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
  loadUsers();
}

// 页码改变
function handlePageChange(page) {
  pagination.value.page = page;
  loadUsers();
}

onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.users-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.stats-row {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
